<template>
  <Spin :spinning="loading" tip="Loading...">
    <div>
      <!-- 考核单维护新增-车厂-详情页面 -->
      <BreakSpace label="考核单信息" :containerStyle="{ marginBottom: '10px' }" />
      <FormPanel ref="formPanel1" :list="formList" :cols="4" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
      <BaseDialog :visible.sync="selectDelearFlag" :title="'经销商选择'" width="850px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <DealerList @close="Delearclose" @save="Delearsave"></DealerList>
      </BaseDialog>
      <BreakSpace label="审核列表" :containerStyle="{ marginBottom: '10px' }" />
      <FilterTable
        ref="table"
        :columns="columns"
        :params="fetchParams"
        :dataSource="dataList"
        :datakey="'items'"
        :onColumnsChange="(columns) => (this.columns = columns)"
        :onRowSelectChange="selectChange"
        :isPagination="false"
        :isSelectColumn="false"
        height="auto"
        :is-select-column="false"
      >
      </FilterTable>
      <div style="margin-bottom: 1rem"></div>
      <!--    <LazyLoadTab v-model="activeName" :tabMenus="menus"></LazyLoadTab>-->
      <div style="padding-top: 3rem"></div>
      <div
        :style="{
        position: 'fixed',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right',
      }"
      >
        <multiuse-button type="primary" :click="saveDialog.bind()">保 存</multiuse-button>
        <!--      <multiuse-button type="primary" :click="zuofei.bind()">作废</multiuse-button>-->
        <multiuse-button @click="closeDialog">关 闭</multiuse-button>
      </div>
    </div>
  </Spin>
</template>
<script>
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import { isFormEmpty } from '@/utils/index';
import { getPartType, quyrPAssess, editSave, deleteOne } from '@/api/claim/factory/CheckSheetMaintain';
import moment from "moment";
import {  getAppId } from '@/assets/js/auth';
import { dictionary } from '@/utils/dictMixin';
export default {
  mixins: [dictionary],
  props: ['rowData'],
  components: {
    DealerList,
  },
  data() {
    return {
      loading: false,
      saveFlag: 0,
      editRow: {},
      dataList: [],
      huanxiajiandataList: [],
      fujiaxiangmudataList: [],
      visible: false,
      visibleDrawer: false,
      selectDelearFlag: false,
      collapse: false,
      infoId: null,
      flterValue: {}, //参数
      columns: this.creatHeader(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      formList: this.createFormList(),
      saveData: null,
    };
  },
  async created() {
    this.loading = true;
    if (getAppId() == 'arcfox') {
      this.formList.find(x => x.fieldName == 'assessClassify').itemList =this.createDictList('5543',[55431001])
    }else{
      this.formList.find(x => x.fieldName == 'assessClassify').itemList =this.createDictList('5543')
    }
    await this.chuqi();
    await this.chuqi1();
    await this.chuqi2();
    await this.getDetailFun(this.rowData.assessId);
    this.loading = false;
  },
  methods: {
    //考核类型
    async chuqi() {
      // const res = await getPartType({ type: 5541 });
      // if (res.resultCode == 200) {
      //   this.formList.find((x) => x.fieldName == 'assessType').initialValue = '';
      //   this.formList.find((x) => x.fieldName == 'assessType').itemList = res.data.map((y) => ({ text: y.codeCnDesc, value: y.codeId }));
      // }
    },
    //考核单状态
    async chuqi1() {
      // const res = await getPartType({ type: 5545 });
      // if (res.resultCode == 200) {
      //   this.formList.find((x) => x.fieldName == 'assessStatus').initialValue = '';
      //   this.formList.find((x) => x.fieldName == 'assessStatus').itemList = res.data.map((y) => ({ text: y.codeCnDesc, value: y.codeId }));
      // }
    },
    //考核分类
    async chuqi2() {
      // const res = await getPartType({ type: 5543 });
      // if (res.resultCode == 200) {
      //   if(getAppId()=='arcfox'){
      //     delete res.data[0]
      //     this.formList.find((x) => x.fieldName == 'assessClassify').initialValue = 55431002;
      //   }
      //   this.formList.find((x) => x.fieldName == 'assessClassify').itemList = res.data.map((y) => ({ text: y.codeCnDesc, value: y.codeId }));
      // }
    },
    async getDetailFun(val) {
      let res = await quyrPAssess(val);
      this.editRow = res.data;
      //为form赋值
      for (let i in res.data) {
        this.formList.map((x) => {
          if (x.fieldName == i) {
            x.initialValue = res.data[i];
          }
          if (x.fieldName == 'wayFiles'){
            x.initialValue = res.data.fileList.map(x => ( {name: x.title, url: x.fileUrl,fileId: x.fileId}));
          }
        });
      }
      console.log(this.formList);
      //为table赋值
      if (200 == res.resultCode) {
        let data = res.data;
        if (isFormEmpty(data)) {
          data = {};
        }
        let records = data.logList;
        if (isFormEmpty(records)) {
          records = [];
        }
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(records);
      }
    },
    formChangeHandle(val) {
      console.log(val);
      this.saveData = val;
    },
    // //搜索获取数据
    // changeHandle(val) {
    //   this.fetchParams = val;
    //   console.log(val);
    // },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    //作废
    async zuofei() {
      this.saveFlag = 2;
      this.saveDialog();
    },
    //提交
    async submit() {
      this.saveFlag = 1;
      this.saveDialog();
      // const res = await zuofeiFun({ ids: rowData.authId, status: '55031002' });
    },
    //保存
    async saveDialog() {
            let a  = this.formList.find((x) => x.fieldName == 'assessAmount').initialValue; 
      let flag = true;
      this.formList.map(x=>{
        if(x.fieldName=='assessType'){
          let b = x.initialValue;
          console.log(x.initialValue,"x.initialValue")
          if((b==55411002||b==55411004)&&(a>0)){
            flag = false;
            this.$notify.error({ title: '提示信息', message:'考核类政策考核金额应为负数' });
          }
          if ((b==55411003||b==55411005)&&(a<0)){
            flag = false;
          this.$notify.error({ title: '提示信息', message:'奖励类政策考核金额应为正数!' });
        }
       }
        })
        //正常的保存逻辑
        if (flag) {
      this.$refs.formPanel1.SUBMIT_FORM();
      this.saveData.wayFiles.map(x => {
        x.title = x.name;
        x.fileUrl = x.url;
      });
      this.saveData.fileList = this.saveData.wayFiles;
      let ids = "";
      this.editRow.fileList.map(x => {
        if (!this.saveData.fileList.find(f => f.fileId == x.fileId)) {
          ids += x.fileId + ",";
        }
      })
      this.saveData.fileIds = ids;
      if (this.saveData !== null) {
        for (let a in this.editRow) {
          if (this.saveData[a]) {
            this.editRow[a] = this.saveData[a];
          }
        }
        if(this.saveData.assessDate){
          this.saveData.assessDate = moment(this.saveData.assessDate).format('YYYY-MM-DD HH:mm:ss');
        }
        this.loading = true;
        let res = await editSave(this.editRow);

        console.log(res);
        if (res.resultCode === 200) {
          this.$emit('save');
          return this.$notify.success({ title: '提示信息', message: '保存成功' });
        } else {
          this.loading = false;
          // this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
          // this.closeDialog();
        }
      }
        }
    },
    //取消操作
    closeDialog() {
      this.$emit('close', { visible: false, data: this.selectedRows, type: 'close' });
    },
    //经销商选择页面
    SelectDelear() {
      this.selectDelearFlag = true;
    },
    //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    //保存
    Delearsave(obj) {
      this.formList.map((x) => {
        if ('dealerCode' == x.fieldName) {
          x.initialValue = obj[0].dealerCode;
        }
        if ('dealerName' == x.fieldName) {
          x.initialValue = obj[0].dealerName;
        }
      });
      this.selectDelearFlag = false;
    },
    chooseOrderNo() {
      this.visible = true;
    },
    add() {},
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请输入经销商代码...',
          initialValue: '',
          readonly: true, // 只读
          rules: [{ required: true, message: '请输入经销商代码...', trigger: 'change' }],
          unitRender: (p) => {
            return (
              <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.SelectDelear()} />
              </div>
            );
          },
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          disabled: true, // 只读
        },
        {
          type: 'INPUT',
          label: '考核单号',
          fieldName: 'assessNo',
          disabled: true, // 只读
        },
        {
          type: 'SELECT',
          label: '考核状态',
          fieldName: 'assessStatus',
          itemList: this.createDictList('5545'),
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '考核类型',
          rules: [{ required: true, message: '请选择...', trigger: 'change' }],
          fieldName: 'assessType',
          itemList: this.createDictList('5541'),
          readonly: true, // 只读
        },
        {
          type: 'DATE',
          label: '考核日期',
          fieldName: 'assessDate',
          valueFormat: 'yyyy-MM-dd', //返回数据格式
        },
        {
          type: 'INPUT',
          label: '考核金额',
          fieldName: 'assessAmount',
          rules: [
            { required: true, message: '请输入考核金额...', trigger: 'blur' },
            { pattern: /^(\-|\+)?\d+(\.\d+)?$/, message: '请输入数字值,小数点后两位...', trigger: 'blur' },
          ],
        },
        {
          type: 'INPUT',
          label: '考核人员',
          fieldName: 'assessByStr',
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '考核分类',
          rules: [{ required: true, message: '请选择考核分类...', trigger: 'change' }],
          itemList: [],
          fieldName: 'assessClassify',
        },
        {
          type: 'INPUT',
          label: '考核原因',
          rules: [{ required: true, message: '请输入考核原因...', trigger: 'change' }],
          selfCols: '4',
          fieldName: 'assessReason',
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          selfCols: '4',
          fieldName: 'assessRemarks',
          placeholder: '请输入备注...',
        },
        {
          type: 'UPLOAD_FILE',
          label: '上传文件',
          fieldName: 'wayFiles',
          placeholder: '上传文件...',
          // rules: [{ required: true, message: '请上传文件...', trigger: 'change' }],
          initialValue: [],
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 10,
            tipText: '（支持PDF、RAR、JPG格式）',
          },
        },
      ];
    },

    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        { title: '审核人', dataIndex: 'checkBy', sorter: true },
        { title: '审核时间', dataIndex: 'checkAt', sorter: true },
        { title: '审核状态', dataIndex: 'statusStr', sorter: true },
        { title: '审核原因', dataIndex: 'checkRemarks', sorter: true },
      ];
    },
  },
};
</script>
<style lang="less" scoped></style>
